import { Component, OnInit } from '@angular/core';
import { BehaviorSubject, of, Observable } from 'rxjs';
import { catchError, map, debounceTime, switchMap } from 'rxjs/operators';
import { SparrowApp } from 'src/app/domain/sparrow-app';
import { SparrowAppService } from 'src/app/service/sparrow-app.service';

@Component({
  selector: 'app-app-search',
  templateUrl: './app-search.component.html',
  styleUrls: ['./app-search.component.css']
})
export class AppSearchComponent implements OnInit {

  constructor(private sysroleService: SparrowAppService) { }

  randomUserUrl = 'https://api.randomuser.me/?results=5';
  searchChange$ = new BehaviorSubject('');
  optionList: SparrowApp[] = [];
  selectedUser?: SparrowApp[];
  isLoading = false;

  onSearch(value: string): void {
    this.isLoading = true;
    this.searchChange$.next(value);
  }

  ngOnInit(): void {

    this.selectedUser = [];
    const getRandomNameList = (name: string) =>
      this.sysroleService.list(null)
        .pipe(
          catchError(() => of({ results: [] })),
          map((res: any) => res.content)
        )
        // .pipe(map((list: any) => list.map((item: any) => `${item.name}`)));
    const optionList$: Observable<SparrowApp[]> = this.searchChange$
      .asObservable()
      .pipe(debounceTime(500))
      .pipe(switchMap(getRandomNameList));
    optionList$.subscribe(data => {
      this.optionList = data;
      this.isLoading = false;
    });
  }

}
